"""
xapper view definitions.
"""

from __future__ import unicode_literals

import contextlib, os
try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO

from django.http import Http404, HttpResponse

from xapper.conf import settings
from xapper.appdef import SilverlightApp

def xap(request, app_name):
  """A view that constructs a .xap file for a given Silverlight app.

  Args:
    app_name  - (unicode) The full name of a Silverlight app as returned from
                `SilverlightApp.name`.

  Returns:
    An HttpResponse whose content is the requested Silverlight app's .xap file.
  """
  if not settings.XAPPER_STATIC_XAP_DIR:
    try:
      silverlight_app = SilverlightApp.get_app(app_name)
    except ValueError:
      raise
      #raise Http404()
    with contextlib.closing(StringIO()) as xapbuf:
      silverlight_app.build_xap(xapbuf)
      xap = xapbuf.getvalue()
  else:
    xap_filename = os.path.join(settings.XAPPER_STATIC_XAP_DIR, app_name + ".xap")
    try:
      with open(xap_filename, "rb") as xap_file:
        xap = xap_file.read()
    except IOError:
      raise Http404()
  return HttpResponse(xap, mimetype="application/x-silverlight-app")
